package cn.zhaozhiqi.template;

import cn.zhaozhiqi.constants.Constants;
import cn.zhaozhiqi.pojo.PointDto;
import cn.zhaozhiqi.properties.TencentProperties;
import cn.zhaozhiqi.utils.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

public class TencentMapTemplate {

    private TencentProperties properties;
    private RestTemplate restTemplate;

    public TencentMapTemplate(TencentProperties properties, RestTemplate restTemplate){
        this.restTemplate = restTemplate;
        this.properties = properties;
    }

    //需要写两个方法进行坐标与坐标之间距离的计算

    /**
     * 计算每个坐标之间加起来的总路程
     * @param list 路程上经过的经纬度坐标的集合
     * @return 总路程
     */
    public BigDecimal computedRealMileage(List<PointDto> list){
        //使用普通for循环将路程加在一起
        BigDecimal realMileage = BigDecimal.ZERO;
        for (int i = 0; i < list.size()-1; i++) {
           BigDecimal distance = distance(list.get(i),list.get(i+1),Constants.TravelMethod.DRIVING);
            realMileage = realMileage.add(distance);
        }
        //加和的值是米，所以除以1000
        realMileage = realMileage.divide(new BigDecimal(1000));
        BigDecimal bigDecimal = realMileage.setScale(2, RoundingMode.HALF_UP);

        return bigDecimal;
    }

    public BigDecimal distance(PointDto from,PointDto to,String mode){
        //使用发送get请求，拼接字符串
        String fromStr = from.getLatitude()+","+from.getLongitude();
        String toStr = to.getLatitude()+","+to.getLongitude();
        String url = String.format(properties.getUrl(),mode,fromStr,toStr,properties.getKey());
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        AssertUtil.isEquals(forEntity.getStatusCodeValue(), HttpStatus.OK.value(),"发送请求至腾讯地图失败！" );
        //将JSON字符串转成JSON对象
        JSONObject jsonObject = JSON.parseObject(forEntity.getBody());
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray rows = result.getJSONArray("rows");
        JSONObject object1 = rows.getJSONObject(0);
        JSONArray elements = object1.getJSONArray("elements");
        BigDecimal distance = elements.getJSONObject(0).getBigDecimal("distance");
        return distance;
    }






}
